# -*- coding: utf-8 -*-

import os
from faker import Faker
from locust import HttpUser, task, between, HttpLocust, constant
from locust import LoadTestShape
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
fake = Faker(locale='zh_CN')
import json


class QuickstartUser(HttpUser):
    host = "http://inbound-uat.tangees.com"
    wait_time = between(1, 3)

    def on_start(self):
        pass

    @task
    def api1(self):
        headers = {
            'Host': 'inbound-uat.tangees.com',
            'Connection': 'keep-alive',
            'Content-Length': '77',
            'pragma': 'no-cache',
            'cache-control': 'no-cache',
            'Origin': 'http://inbound-uat.tangees.com',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36',
            'Content-Type': 'application/json',
            'Accept': '*/*',
            'Referer': 'http://inbound-uat.tangees.com/enterprise-wechat/conversation-archive',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cookie': 'sessionId=.eJw1zjkOAjEMQNG7pKZI4iU2l0FeEkEBQgNUiLszEqL6zS_eu5zWNh_ncnxur3kop0uWY7Hw5Q5C0YkokaDFXu0QThDKyOhT3IauPlwigQ2cRQZJTxB01pXM3ZFaR8V05FAhqGuw1OqrSzRjqBk6B2KznjYMA6ytskPuc7vabd6ef9rrMbcfj-uAfZZqzuFqI3WCu5TPFyVxO98.FIoHPQ.qSvUyOtTASjPFtU9lefYWhPkjNY; accountCenterSessionId=.eJw9jr1Ow0AQhN_laorb9fnOTg2KQMQ0CRZurL39UWIsI8UBpCDenVMKupnRzOj7cZ-rnseTuI2LQE3iWgwqyRQ1WCyazd250c66Ht3GaF612FvfSDCyCLGFbACc0UstGYwrny1hy2w5WVTQGpsmBy-YAWtsTRNiQGPKjMBEvm6TTy1VAjEKUaPQsDQZtWqNIGrlfSoBhtIl8G1FsXAtqjKu9KXj5WOU_A-43gDf9u9-2DN0_eHS9U9zd_J-t93hc_8YhpK93HPorgcYptepmx6u5ZCPtCw6l_G3Zvf7B_N-V58.FIoSeg.odZMPC_LBzwZoK7Cifhq1sqvpws',

        }

        payload = {"pageNum": 1, "pageSize": 10, "keyword": "消息", "customerIds": [], "staffIds": []}
        with self.client.post(url='/jike-web/msgaudit/message/global-list', headers=headers, data=json.dumps(payload),
                              catch_response=True, name="全局搜索") as response:
            print(response.text)
            if response.status_code == 200:
                try:
                    assert json.loads(response.text)['errCode'] == 0
                except:
                    response.failure("Timeout")
            else:
                response.failure(response.status_code)

    def on_stop(self):
        pass


class StagesShape(LoadTestShape):
    """
    在不同的阶段 具有不同的用户数和 产生率的 图形形状


    参数解析:
        stages ：字典列表，每个字典都具有下列这些键值的阶段:
            duration -- 持续时间，  经过多少秒后，进入到下个阶段
            users -- 总用户数
            spawn_rate -- 产生率，即每秒启动/停止的用户数
            stop -- 可以在特定阶段停止测试的值
        stop_at_end -- 可以在所有阶段设置运行后停止

    """

    stages = [
        {"duration": 300, "users": 15, "spawn_rate": 2},
        # {"duration": 300, "users": 10, "spawn_rate": 2},
        # {"duration": 300, "users": 20, "spawn_rate": 2}
    ]

    def tick(self):

        run_time = self.get_run_time()

        for stage in self.stages:
            if run_time < stage['duration']:
                tick_data = (stage['users'], stage['spawn_rate'])
                return tick_data

        return None


if __name__ == "__main__":
    current_file_path = os.path.abspath(__file__)
    os.system(f"locust -f {current_file_path} --web-host=127.0.0.1")
